$(function () {
    var _addPost = $('#addNewPost');
	
    _addPost.click(function () {
        var saveData = {"type":window.location.href, "id":0, "op":7};
        if (!PINBOARD.common.newIsLogin(null, saveData))return false;
        PINBOARD.common.isLogin();
        POST.collect.show();
        return false;
    });

});

var PINBOARD = PINBOARD || {};
PINBOARD.photoLoadErr = function (obj, type, size) {
    var _base = 'http://s11.libmibo.com/images/pinboard/default/',
        _url = '/collect/resize',
        _src = '',
        $obj = $(obj),
        _width = _height = size + 'px',
        _postData = {
            'id':$obj.attr('id'),
            'url':$obj.attr('src'),
            'state':$obj.attr('state')
        };

    //用于大图展示
    var Regx = /^[A-Za-z]/;
    if (!_postData.id || Regx.test(_postData.id)) {
        _postData.id = $obj.attr('picId');
    }

    try {
        Interface.ajaxPost(_postData, _url, function (data) {
            //var _data = $.parseJSON(data);
//alert(data);
            if (typeof data == 'string') {
                var _imgurl = data + "?t=" + new Date().valueOf();
                var _img = new Image();
                _img.onload = function () {
                    //alert("onload");
					$obj.attr('src', _imgurl);
                    _img.onload = null;
                };
                _img.onerror = function () {
                   // alert('加载异步图片失败');
                    _src = _base + 'default_' + size + '.png';
                    $obj.attr('src', _src).css({'height':_width, 'width':_width});
                };
				//alert(_imgurl);
                _img.src = _imgurl;
            } else {
                _src = _base + 'default_' + size + '.png';
                $obj.attr('src', _src).css({'height':_width, 'width':_width});
            }
            ;
        }, null);
    } catch (err) {//alert("catch到错误了");
        _src = _base + 'default_' + size + '.png';
        $obj.attr('src', _src).css({'height':_height, 'width':_width});
    }
    ;
};
PINBOARD.imgLoadErr = function (obj, type, size) {
    var _base = 'http://s11.libmibo.com/images/pinboard/default/',
        _src = '',
        _width = _height = size + 'px';
    if (type == 'avatar') {
        _src = _base + 'default_avatar_' + size + '.png';
    } else if (type == 'photo') {
        _src = _base + 'default_' + size + '.png';
    }
    $(obj).attr('src', _src).css({'height':_height, 'width':_width});
};


//格式化
PINBOARD.format = {
    blog:function (blogUrl) {
        return "http://" + blogUrl + ".icaitu.com";
    },
    post:function (postId) {
        return "/post/" + postId;
    },
    post_private:function (postId) {
        return "/private/post/id/" + postId;
    },
    postEdit:function (postId) {
        return "/collect/edit/id/" + postId;
    },
    board:function (boardId) {
        return "/board/id/" + boardId;
    },
    boardEdit:function (boardId) {
        return "/board/edit/id/" + boardId;
    },
    img:function (url) {
        return url;
    },
    time:function (second) {
        var time = parseInt(second);
        var now = new Date().getTime() / 1000;//js是根据微秒计算时间
        var gap = now - time;
        if (gap < 60) {
            return "刚刚";
        } else if (gap < 3600) {
            return Math.round(gap / 60) + "分钟前";
        } else if (gap < 86400) {
            return Math.round(gap / 3600) + "小时前";
        } else if (gap < 604800) {
            return Math.round(gap / 86400) + "天前";
        } else if (gap < 2592000) {
            return "约" + Math.round(gap / 604800) + "周前";
        } else if (gap < 7776000) {
            return "约" + Math.round(gap / 2592000) + "月前";
        } else {
            time = new Date(time * 1000);
            return time.getFullYear() + "年" + (time.getMonth() + 1) + "月" + time.getDate() + "日" + " " + time.getHours() + "时" + time.getMinutes() + "分";
        }
    },

    version:1
};

//中文字符串的处理
PINBOARD.cn = {//2个英文算1个中文
    subString:function (str, count) {//按中文字符截取
        count = count * 2;
        var r = /[^\x00-\xff]/g;
        if (str.replace(r, "mm").length > count) {
            var m = Math.floor(count / 2);
            for (var i = m; i < str.length; i++) {
                if (str.substr(0, i).replace(r, "mm").length >= count) {
                    return str.substr(0, i);
                }
            }
        }//end if
        return str;
    },
    getLength:function (str) {//获取中文字数
        return parseInt(str.replace(/[^\x00-\xff]/g, "mm").length / 2);
    },

    version:1
};

PINBOARD.goTop = function (selecter) {//回顶部,selecter,jquery选择器，第二屏时才能看到
    var $btn = $(selecter).hide();
    var isIE = !!window.ActiveXObject;
    var isIE6 = isIE && !window.XMLHttpRequest;
    var scrollTop=$(window).scrollTop();
    setInterval(function(){

        var tp=$(window).scrollTop();
        if(tp==scrollTop && tp<200){
            return false;
        }else{
            scrollTop=tp;
            if(scrollTop>200){
                show(true);
            }else{
                show(false);
            }
        }
    },500);

    var show=function(show){
        if(show){
            $btn.fadeIn();
            if(isIE6){
            var top=scrollTop+$(window).height()-60+'px';
                $btn.css({position:"absolute",right:"10px",top:top});
            }
        }else{
            $btn.fadeOut();
        }
    };
    $btn.click(function () {
        $('html, body').animate({scrollTop:0});
        return false;
    });
};//end goTop

PINBOARD.common = {
    isLogin:function () {
        if (PINBOARD.myBlog.id == '') {
            //this.popLogin();
            //window.location="/";
            return false;
        }
        return true;
    },
    newIsLogin:function (e, d) {
        var le = e;
        var ld = d;
        var isLogin ;
        if (PINBOARD.myBlog.id == '' || isLogin == 1) {
            this.popLogin(le, ld);
            //window.location="/";
            return false;
        }
        return true;
    },
    popLogin:function (le, ld) {
        var lle = le;
        var lld = ld;
        var is = 0;
        //保持原来的注册和第三方登录的超链接地址
        var oldRegist = PINBOARD.pop.regist;
        var thirdLogin=[];
        for(var i = 0;i<9;i++){
        	thirdLogin[i] = PINBOARD.pop.a[i];
        }
        //-----end
        if (arguments.length == 2) {
            //lle = le;
            //lld = ld;
            is = 1;
            	//注册的时候，判断r_type==0,是等于0的时候字符串拼装要换一种方式
            	if(lld.type == 0){
            		PINBOARD.pop.regist += "?r_type=" + lld.type + "&r_value=" + lld.url + "&id="+ lld.id +"&op=" + lld.op +"&bid="+lld.blogId+"&k="+lld.k+"&type="+lld.btype;
            	}else{
            		PINBOARD.pop.regist += "/r_type/" + lld.type + "/r_value/id=" + lld.id + "&op=" + lld.op+"&bid="+lld.blogId+"&url="+lld.url+"&k="+lld.k+"&type="+lld.btype;
            	}
            for (var i = 0; i < 9; i++) {
            	//第三方登录的时候，判断r_type==0，是等于0的时候字符串拼装要换一种方式
            	if(lld.type == 0){
            		PINBOARD.pop.a[i] += "?r_type=" + lld.type + "&r_value= " +lld.url + "&id="+ lld.id +"&op=" + lld.op +"&bid="+lld.blogId+"&k="+lld.k+"&type="+lld.btype;
            	}else{
            		PINBOARD.pop.a[i] += "/r_type/" + lld.type + "/r_value/id=" + lld.id + "&op=" + lld.op+"&bid="+lld.blogId+"&url="+lld.url+"&k="+lld.k+"&type="+lld.btype;
            	}
                
            }
        }
        var pop = "<div style='width:641px;height:310px;position:relative;'>" + "<div style='width:641px;height:310px;position:relative;'>"
            + "<div id='title'><span>登录爱采图，采尽天下美图</span><span class='txt'>在这里你可以随心所欲采集图片！</span><div id='close'></div></div>" + "<div id='login'>"
            + "<div class='alertTip color-error' id='userTip' style='display: none; top:60px; left: 90px;'><div id='nameTipText' class='alertTip-txt'></div><div class='alertTip-arrow'></div><a class='hideBtn'></a></div>"
            + "<div class='alertTip color-error' id='pwdTip' style='display: none; top:110px; left: 90px;'><div id='passTipText' class='alertTip-txt'></div><div class='alertTip-arrow'></div><a class='hideBtn'></a></div>"
            + "<form id='popLoginForm'>"
            + "<table><form method='post' action='" + PINBOARD.pop.table + "' id='login_form'>"
            + "<tr height='20px'><td width='70px'></td><td></td></tr>"
            + "<tr class='name'>" + "<td class='tips'><span>帐号:</span></td>" + "<td ><label for='input_username' id='input_username_tips'>邮箱/手机/个性化帐号</label>"
            + "<input type='text' id='input_username'/></td></tr>"
            + "<tr class='name'><td class='tips'><span>密码:</span></td>" + "<td ><label id='input_password_tips' for='input_password'>请输入密码</label>"
            + "<input id='input_password' type='password'/></td></tr>"
            + "<tr class='forget'>" + "<td></td><td><div><input style='padding:0' type='checkbox' checked='checked' name='rememberMe'/><label for='checkbox'><span>两周内自动登录</span></label>"
            + "<a href='" + PINBOARD.pop.forget + "'>忘记密码?</a></div></td></tr>"
            + "<tr class='submit'><td></td><td><input type='submit' id='login_a' value=''/></td></tr>"
            + "<tr><td></td><td></td></tr></form></table></form></div>"
            + "<div id='regist'><div></div><ul><li>还没有注册帐号？</li>"
            + "<li style='margin-top:15px' ><a id='regist_a' href='" + PINBOARD.pop.regist + "'></a></li>"
            + "<li style='margin-top:20px'>使用合作网站登录:</li>"
            + "<li class='others'>"
            + "<span style='margin-top:0'>"
            + "<a title='QQ' href='" + PINBOARD.pop.a[0] + "' id='qq'></a>"
            + "<a title='新浪微博' href='" + PINBOARD.pop.a[1] + "' id='sina'></a>"
            + "<a title='腾讯微博' href='" + PINBOARD.pop.a[2] + "' id='tencent'></a>"
            + "<a title='人人网' href='" + PINBOARD.pop.a[3] + "' id='renren'></a>"
            + "<a title='开心网' href='" + PINBOARD.pop.a[4] + "' id='kaixin'></a>"
            + "<a title='网易微博' href='" + PINBOARD.pop.a[5] + "' id='wangyi'></a>"
            + "<a title='搜狐微博' href='" + PINBOARD.pop.a[6] + "' id='souhu'></a>"
            + "<a title='豆瓣网' href='" + PINBOARD.pop.a[7] + "' id='douban'></a>"
            + "<a title='饭否' href='" + PINBOARD.pop.a[8] + "' id='fanfou'></a>"
            + "</span></li></ul></div></div>";

        var a = Interface.tipWindow(null, pop);
        $("#input_username").live('focus', function (event) {
            $("#userTip").hide();
            $(this).prev().hide();
        });
        $("#popLoginForm").live('submit', function (event) {
            $("#login_a").click();
            return false;
        });

        $("#input_username").live('blur', function (event) {
            var $input = $(this);
            var val = $input.val();
            if (val == "") {
                $(this).prev().show()
            }
        });
        $("#input_password").live('focus', function (event) {
            $("#pwdTip").hide();
            $(this).prev().hide();
        });
        $("#input_password").live('blur', function (event) {
            var $input = $(this);
            var val = $input.val();
            if (val == "") {
                $(this).prev().show()
            }
        });
        $("#close").bind('click', function (event) {
        	//在close弹出框的时候将注册和第三方的超链接还原成原来的内容，这样在头部再次点击注册的时候就不会发生传递两次的情况
            PINBOARD.pop.regist = oldRegist;
            for(var i = 0;i<9;i++){
            	PINBOARD.pop.a[i] = thirdLogin[i];
            }
            a.hideAndUnload();
        })
        $(".hideBtn").live('click', function (event) {
            $(this).parent().hide();
        })

        $("#login_a").bind('click', function (event) {
            $("#userTip").hide();
            $("#pwdTip").hide();
            if ($("#input_username").val() == "") {
                $("#nameTipText").html("请输入帐号");
                $("#userTip").show();
            } else if ($("#input_password").val() == "") {
                $("#passTipText").html("请输入密码");
                $("#pwdTip").show();
            } else {
                Interface.login($("#input_username").val(), $("#input_password").val(), lld.type, lld.id, lld.op,lld.blogId,lld.url,lld.k,lld.btype, function (data) {
                    var reData = $.parseJSON(data);//返回值是一个字符串，要转换成json类型
                    if (reData.status == 0) {
                        if (reData.infor["username"]) {
                            $("#nameTipText").html(reData.infor["username"]);
                            $("#userTip").show();
                        }
                    } else if (reData.status == 1) {
                        if (is == 0) {
                            a.hide();
                            window.location.reload();
                        }
                        else {
                            a.hide();
                            if(reData.infor["r_type"] != ""){
                            	 window.location.href = reData.infor["r_url"];
                            }
                            //window.location.reload();
                            //alert(reData.infor["r_type"]);
                            //PINBOARD.myBlog.id='1';
                            //PINBOARD.bet._likeHandle(lle);
                        }
                        //loginedMessage = reDate;//取数据
                    }
                });
            }
            return false;
        });
    }//end popLogin
};
//js的字符解析
function URLEncode(clearString) {
    var output = '';
    var x = 0;
    clearString = clearString.toString();
    var regex = /(^[a-zA-Z0-9-_.]*)/;
    while (x < clearString.length) {
        var match = regex.exec(clearString.substr(x));
        if (match != null && match.length > 1 && match[1] != '') {
            output += match[1];
            x += match[1].length;
        } else {
            if (clearString.substr(x, 1) == ' ') {
                //原文在此用 clearString[x] == ' ' 做判断, 但ie不支持把字符串当作数组来访问,
                //修改后两种浏览器都可兼容
                output += '+';
            } else {
                var charCode = clearString.charCodeAt(x);
                var hexVal = charCode.toString(16);
                output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
            }
            x++;
        }
    }
    return output;
}